package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.DishService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private DishService dishService;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {

        Long dishId = shoppingCartDTO.getDishId();
        Long setmealId = shoppingCartDTO.getSetmealId();
        String dishFlavor = shoppingCartDTO.getDishFlavor();
        Long userId = BaseContext.getCurrentId();

        //首先根据传入的值加上用户id查询这条数据是否在该用户的购物车中出现，如果出现，数量+1
        ShoppingCart sc=shoppingCartMapper.getByShoppingCartDTO(shoppingCartDTO,userId);
        if (sc!=null){
            //修改该套餐或菜品的数量
            shoppingCartMapper.updateAddOne(sc.getId());
            return;
        }

        ShoppingCart shoppingCart = new ShoppingCart();

        //一个菜品或者一个套餐是一条购物车数据
        if (dishId!=null){
            DishVO dishVO = dishService.getById(dishId);

            shoppingCart.setName(dishVO.getName());
            shoppingCart.setImage(dishVO.getImage());
            shoppingCart.setUserId(userId);
            shoppingCart.setDishId(dishId);
            shoppingCart.setDishFlavor(dishFlavor);
            shoppingCart.setAmount(dishVO.getPrice());
        }else{
            //新增一个套餐购物车数据
            Setmeal setmeal = setmealMapper.getById(setmealId);
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setUserId(userId);
            shoppingCart.setSetmealId(setmealId);
            shoppingCart.setAmount(setmeal.getPrice());
        }
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());

        shoppingCartMapper.insert(shoppingCart);


    }

    /**
     * 查看购物车
     * @return
     */
    @Override
    public List<ShoppingCart> list() {
        //获取线程中的用户id
        Long userId = BaseContext.getCurrentId();
        //根据用户id查询该用户的购物车
        List<ShoppingCart> list=shoppingCartMapper.getListByUserId(userId);
        return list;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clean() {
        //获取线程中的用户id
        Long userId = BaseContext.getCurrentId();
        //根据用户id，删除该用户购物车数据
        shoppingCartMapper.deleteByUserId(userId);
    }
}
